#include "widget.h"
#include "ui_widget.h"
#include "stdlib.h"

Widget::Widget(QWidget *parent) :
    QWidget(parent),
    ui(new Ui::Widget)
{

    ui->setupUi(this);
    timer = new QTimer(this);
    timer->setInterval(10);
    connect(timer, SIGNAL(timeout()), this, SLOT(disp_img()));
    global_vars_init();
    ret = media_device_alloc(&media);
    if (ret < 0) {
        printf("No enough memory\n");
    }
    ret = media_device_open(&media);

    ret = media_device_prepare(&media);

    ret = media_device_start(&media);
    printf("start timer \n ");
    timer->start();
}

Widget::~Widget()
{
    media_device_stop(&media);
    media_device_cleanup(&media);
    media_device_close(&media);
    media_device_free(&media);
    v4l2_info("=*= success =*=\n");
    delete ui;


}
void Widget::disp_img()
{
    struct video_channel *video_ch;
    int i, ret;
    int buf_id;
    static int frame_cnt=0;
    
    video_ch =  media.v4l2_dev->video_ch;
    do {
        for (i = 0; i < NUM_SENSORS; i++) {
            if (video_ch[i].on) {
                /* DQBUF */
                ret = dqueue_buffer(i, &video_ch[i]);
                if (ret < 0)
                    return ;

                /* Save to file or playback */
                    /* Playback */
                    buf_id = video_ch[i].cur_buf_id;
                    camera_image = new QImage(video_ch[i].buffers[buf_id].planes[0].start,SET_WIDTH,SET_HEIGHT,QImage::Format_RGB888);
                    ui->disp_label->setPixmap(QPixmap::fromImage(*camera_image));
                    if (ret < 0)
                       return ;
            }
        }

        /* QBUF */
        for (i = 0; i < NUM_SENSORS; i++) {
            if (video_ch[i].on)
                queue_buffer(video_ch[i].cur_buf_id, &video_ch[i]);
        }
	frame_cnt++;
        /* Record enter time for every channel */
       /*
	    for (i = 0; i < NUM_SENSORS; i++) {
               if (video_ch[i].on) {
                gettimeofday(&video_ch[i].tv1, NULL);
//                printf("%us : %u ms \n ",video_ch[i].tv1.tv_sec,video_ch[i].tv1.tv_usec / 1000);
               }

           }
	*/
    } while(0);
    if(0==frame_cnt % 300)//修改成每300帧休眠一次
    {
    	media_device_stop(&media);
   	media_device_cleanup(&media);
    	media_device_close(&media);
    	media_device_free(&media);

        system("echo enabled > /sys/class/tty/ttyLP0/power/wakeup");
  	system("echo mem > /sys/power/state");
  	printf("wake up by ttyLP0\n");
        /*唤醒后重新初始化  */
	global_vars_init();      
	media_device_alloc(&media); 
        media_device_open(&media);
	media_device_prepare(&media);
	media_device_start(&media);

	frame_cnt = 0;
    }	

}
